<?php

namespace app\zucai\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

use app\zucai\model\Account;
use app\zucai\model\User_recharge;

use app\zucai\model\PutCash;

use think\Db;
use think\Exception;

/**
 * zucai 后台模块
 */
class User extends Admin
{
    //用户详情
    public function index()
    {
        // 获取排序
        $order = $this->getOrder();
        // 获取筛选
        $map = $this->getMap();
        $fla = Db::name('admin_user')->field('role')->where('id', is_signin())->find();

        if ($fla['role'] == 1) {
            $data = Db::name('user')->order($order)->where($map)->paginate();
            $a = [
                ['__INDEX__', '序号'],
                ['uid', '所属服务商', 'callback', function ($uid) {
                    $uname = Db::name('admin_user')->where('id', $uid)->field('nickname')->find();
                    return $uname['nickname'];
                }],
                ['id', 'ID'],
                ['user', '真实姓名'],
                ['name', '昵称'],
                ['mobile', '联系电话'],
                ['identity', '身份证'],
                ['money', '余额'],
                ['blockmoney', '冻结金额'],
                ['allmoney', '总充值金额'],
                ['timoney', '总提款金额'],
                ['create_time', '注册时间', 'datetime'],
                ['status', '状态', 'switch'],
            ];
        } else {
            $data = Db::name('user')->order($order)->where($map)->where('uid', is_signin())->paginate();
            $a = [
                ['__INDEX__', '序号'],
                ['id', 'ID'],
                ['user', '真实姓名'],
                ['name', '昵称'],
                ['mobile', '联系电话'],
                ['identity', '身份证'],
                ['money', '余额'],
                ['blockmoney', '冻结金额'],
                ['allmoney', '总充值金额'],
                ['timoney', '总提款金额'],
                ['create_time', '注册时间', 'datetime'],
                ['status', '状态', 'switch'],
            ];
        }

        $con = Db::name('admin_user')->where('status', 1)->column('id,nickname');
        return ZBuilder::make('table')
            ->setPageTitle('用户列表')
            ->setSearch(['id' => '用户ID', 'user' => '真实姓名','name' => '昵称', 'mobile' => '联系电话', 'identity' => '身份证'],'','',true)// 设置搜索参数
            ->addOrder('money,id,create_time')// 添加排序
            ->setTableName(true)
            ->addTopButtons('enable,disable')// 批量添加顶部按钮
            ->addColumns($a)
            ->hideColumn('uid', '1')
            ->addFilter('uid', $con)
            ->addFilterList('status', ['禁用', '启用'], '0,1')
            ->setColumnWidth('identity,create_time,', 160)
			->setColumnWidth('mobile', 120)
            ->setColumnWidth('__INDEX__', 50)
            ->setRowList($data)
            ->fetch();
    }

    //充值记录
    public function recharge()
    {
        // 获取排序
        $order = $this->getOrder();
        // 获取筛选
        $map = $this->getMap();

        $da = [
            0 => '未付款',
            1 => '成功',
        ];
        $fla = Db::name('admin_user')->field('role')->where('id', is_signin())->find();

        if ($fla['role'] == 1) {
            $data = User_recharge::
            order('time DESC')
                ->order($order)->where($map)->paginate();
            $a = [
                ['__INDEX__', '序号'],
                ['nickname', '所属服务商'],
                ['order_id', '订单编号'],
                ['user', '真实姓名'],
                ['name', '昵称'],
                ['money', '充值金额'],
                ['type', '充值方式'],
                ['time', '充值时间'],
                ['status', '状态', $da],
            ];
        } else {
            $data = User_recharge::
            order('time DESC')
                ->where('aid', is_signin())
                ->order($order)->where($map)->paginate();

            $a = [
                ['__INDEX__', '序号'],
                ['order_id', '订单编号'],
                ['user', '真实姓名'],
                ['name', '昵称'],
                ['money', '充值金额'],
                ['type', '充值方式'],
                ['time', '充值时间'],
                ['status', '状态', $da],
            ];
        }

        // Excel导出
        $btn_table = [
            'title' => '导出充值记录',
            'icon' => 'fa fa-fw fa-table',
            'href' => url('excel_get'),
            'class' => 'btn btn-success  confirm'
        ];

        return ZBuilder::make('table')
            ->setTableName('user_recharge')
            ->addTopButtons(['table' => $btn_table])
            ->setPageTitle('充值记录')
            ->setSearch(['order_id' => '订单编号', 'user' => '真实姓名', 'name' => '昵称'],'','',true)// 设置搜索参数
            ->addOrder('money,time')// 添加排序
            ->addColumns($a)
			->setColumnWidth('time', 130)
            ->addFilter('nickname,user,order_id')
            ->addFilter('status', $da)
            ->addFilter('type')
            ->setRowList($data)
            ->fetch();

    }

    /**
     * @return mixed
     * 导出充值记录表格
     * gxq <know1111@vip.qq.com>
     */
    public function excel_get()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $post = $this->request->post();
            if (!$post) $this->error('违规操作');

            if (!isset($post['time'])) $this->error('请选择时间范围');
            if (!$post['time'][0] || !$post['time'][1]) $this->error('请选择时间范围');

            $time1 = $post['time'][0];
            $time2 = $post['time'][1];
            $fla = Db::name('admin_user')->field('role')->where('id', is_signin())->find();
            if ($fla['role'] == 1) {
                $data = User_recharge::
                where('time', '>=', $time1)
                    ->where('time', '<=', $time2)
                    ->select();
            } else {
                $data = User_recharge::
                where('time', '>=', $time1)
                    ->where('time', '<=', $time2)
                    ->where('aid', is_signin())
                    ->select();
            }
            $user2 = array();
            foreach ($data as $k => $v) {
                $user2[$k][1] = $v['nickname'];
                $user2[$k][2] = $v['order_id'];
                $user2[$k][3] = $v['user'];
                $user2[$k][4] = $v['name'];
                $user2[$k][5] = $v['money'];
                $user2[$k][6] = $v['type'];
                $user2[$k][7] = $v['time'];
                switch ($v['status']) {
                    case 0:
                        $user2[$k][8] = '未付款';
                        break;
                    case 1:
                        $user2[$k][8] = '成功';
                        break;
                    default :
                        $this->error('违规操作');
                };
            }

            $headArr = array('所属服务商', '订单号', '真实姓名', '昵称', '充值金额', '充值方式', '下单时间', '充值状态');
            $filename = "充值记录表";
            //dump($user2);exit;
			
            $this->getExcel($filename, $headArr, $user2);
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['daterange', 'time']
            ])
            ->method('post')
            ->isAjax(false)
            ->fetch();
    }


    /**
     * @return mixed
     * 提现记录
     * gxq <know1111@vip.qq.com>
     */
    public function putCash()
    {
        // 获取排序
        $order = $this->getOrder();
        if (!$order) {
            $order = 'status,create_time desc';
        }
        // 获取筛选
        $map = $this->getMap();

        //解决筛选条件问题
        if (isset($map['put_cash.status'])) {
            $map['zc_put_cash.status'] = $map['put_cash.status'];
            unset($map['put_cash.status']);
        }
        if (isset($map['user_card.cardname'])) {
            $map['cardname'] = $map['user_card.cardname'];
            unset($map['user_card.cardname']);
        }
        if (isset($map['user_card.username'])) {
            $map['username'] = $map['user_card.username'];
            unset($map['user_card.username']);
        }
        if (isset($map['user_card.type'])) {
            $map['type'] = $map['user_card.type'];
            unset($map['user_card.type']);
        }
        if (isset($map['user_card.carnumber'])) {
            $map['carnumber'] = $map['user_card.carnumber'];
            unset($map['user_card.carnumber']);
        }
        if (isset($map['user.mobile'])) {
            $map['mobile'] = $map['user.mobile'];
            unset($map['user.mobile']);
        }

        if (is_signin() != 1) {
            $login['d.id'] = is_signin();

            $list = [
                ['right_button', '操作', 'btn'],
                ['status', '状态', 'status', '', [1 => '待审核:warning', 2 => '通过:info', 3 => '未通过:default', 4 => '已打款:success']],
                //['id','ID'],
                ['name', '用户昵称'],
                ['avatar', '头像', 'img_url'],
                ['money', '提现金额'],
                ['username', '银行卡持有人'],
                ['type', '银行卡类型'],
                ['cardname', '银行名称'],
                ['carnumber', '银行卡号'],
                ['mobile', '手机号'],
                ['create_time', '申请时间'],
            ];
        } else {
            $login = null;

            $list = [
                ['right_button', '操作', 'btn'],
                ['status', '状态', 'status', '', [1 => '待审核:warning', 2 => '通过:info', 3 => '未通过:default', 4 => '已打款:success']],
                ['nickname', '所属代理商'],
                ['name', '用户昵称'],
                ['avatar', '头像', 'img_url'],
                ['money', '提现金额'],
                ['username', '银行卡持有人'],
                ['type', '银行卡类型'],
                ['cardname', '银行名称'],
                ['carnumber', '银行卡号'],
                ['mobile', '手机号'],
                ['create_time', '申请时间'],
            ];
        }


        $cash = PutCash::alias('a')
            ->join('zc_user b', 'a.user_id=b.id')
            ->join('zc_user_card c', 'a.card_id=c.id')
            ->join('zc_admin_user d', 'b.uid=d.id')
            ->field('a.id,a.money,a.create_time,a.update_time,a.status,b.name,b.mobile,b.avatar,c.username,type,cardname,carnumber,d.nickname,b.uid')
            ->order($order)
            ->where($map)
            ->where($login)
            ->select();

        foreach ($cash as $k => $v) {
            if ($v['avatar'] >= 1 && $v['avatar'] <= 11) $cash[$k]['avatar'] = get_file_path($v['avatar']);
        }

//        //批量通过
//        $btn_access_2 = [
//            'title' => '批量通过',
//            'icon' => 'fa fa-fw fa-key',
//            'href' => url('adopt', ['type' => 2]),
//            'class' => 'btn btn-warning ajax-post confirm'
//        ];
//
//        // 批量打款
//        $btn_access_4 = [
//            'title' => '批量打款',
//            'icon' => 'fa fa-fw fa-key',
//            'href' => url('adopt', ['type' => 4]),
//            'class' => 'btn btn-warning ajax-post confirm'
//        ];

        // Excel导出
        $btn_table = [
            'title' => '导出提现记录',
            'icon' => 'fa fa-fw fa-table',
            'href' => url('excel_put'),
            'class' => 'btn btn-success  confirm'
        ];

        return ZBuilder::make('table')
            ->setTableName(true)
            ->addOrder('money,create_time,update_time')// 添加排序
            ->addFilter(['user_card.username', 'user_card.type', 'user_card.cardname', 'user.mobile', 'user_card.carnumber'])// 添加筛选
            ->addFilter('put_cash.status', ['', '待审核', '通过', '未通过', '已打款'])
            ->hideCheckbox()
            ->addColumns($list)
            ->addRightButtons(['edit' => ['title' => '处理']])
            ->replaceRightButton(['status' => 3], '')
            ->replaceRightButton(['status' => 4], '')
            ->addTopButtons(['table' => $btn_table])
            ->setColumnWidth('carnumber', 155)
            ->setColumnWidth('create_time,update_time', 135)
            ->setColumnWidth('avatar', 50)
            ->setColumnWidth('right_button', 35)
            ->setColumnWidth('cardname', 120)
            ->setColumnWidth('status', 60)
            ->setRowList($cash)
            ->fetch();
    }


    public function edit($id = 0)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (!$post) $this->error('请选择状态');

            $cash = Db::name('put_cash')->alias('a')->where('a.id', $id)->join('zc_user b', 'a.user_id=b.id')->field('b.uid,a.money as a_money,b.money as b_money,a.id,a.user_id,a.status,b.user,b.name,b.blockmoney,b.tx_money,b.timoney')->find();
            //dump($cash);exit;
            if ($cash['uid'] != is_signin()) $this->error('违规操作');
            if ($cash['status'] == 3 || $cash['status'] == 4) $this->error("该提现申请已被确认为'未通过'或'已打款'状态，不可修改");
            $post['update_time'] = date('Y-m-d H:i:s', time());
            Db::startTrans();//事务开始
            try {
                if ($s = Db::name('put_cash')->where('id', $id)->update($post)) {
                    if ($post['status'] == 3) {
                        $add['money'] = $cash['b_money'];
                        $add['uid'] = $cash['user_id'];
                        $add['type'] = 4;
                        $add['caizhong'] = '足彩';
                        $add['caicontent'] = '提现申请未通过审核';
                        $add['username'] = $cash['user'];
                        $add['name'] = $cash['name'];
                        $add['lastmoney'] = $cash['b_money'] + $cash['a_money'];
                        $add['dmoney'] = $cash['blockmoney'];
                        $add['time'] = date('Y-m-d H:i:s', time());

                        if (Db::name('account')->insert($add)) {
                            if (Db::name('user')->where('id', $cash['user_id'])->update(['money' => $add['lastmoney'], 'tx_money' => $cash['tx_money'] + $cash['a_money'], 'timoney' => $cash['timoney'] - $cash['a_money']])) {
                                Db::commit();
                                $this->success('修改状态成功', 'putcash');
                            } else {
                                throw new Exception();
                            }
                        } else {
                            throw new Exception();
                        }
                    } else {
                        Db::commit();
                        $this->success('修改状态成功', 'putcash');
                    }
                } else {
                    throw new Exception();
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error('修改状态失败');
            }
        }

        $cash = Db::name('put_cash')
            ->alias('a')
            ->join('zc_user b', 'a.user_id=b.id')
            ->join('zc_user_card c', 'a.card_id=c.id')
            ->field('a.id,a.money,a.create_time,a.update_time,b.name,b.mobile,b.avatar,c.username,type,cardname,carnumber')
            ->where('a.id', $id)
            ->find();

        if ($cash['avatar'] >= 1 && $cash['avatar'] <= 11) $cash['avatar'] = get_file_path($cash['avatar']);
        return ZBuilder::make('form')
            ->addFormItems([
                ['static', 'money', '提现金额'],
                ['static', 'carnumber', '银行卡号'],
                ['static', 'cardname', '银行名称'],
                ['static', 'type', '银行卡类型'],
                ['static', 'username', '银行卡持有人'],
                ['static', 'name', '用户昵称'],
                ['static', 'mobile', '联系手机'],
                ['static', 'create_time', '申请时间'],
                ['radio', 'status', '状态', '注:<code>未通过</code>选项会将金额原路返回给用户，并且设置为<code>未通过</code>或<code>已打款</code>状态后将<code>不可更改</code>。', [2 => '通过', 3 => '未通过', 4 => '已打款']]
            ])
            ->setFormData($cash)
            ->fetch();

    }


//    /**
//     * @return mixed
//     * 批量操作
//     * gxq <know1111@vip.qq.com>
//     */
//    public function adopt()
//    {
//        $post = $this->request->post();
//
//        if (!$post) $this->error('违规操作');
//        $type = input('type');
//        if (!isset($type)) $this->error('违规操作');
//
//        $where['id'] = array('in', array());
//        foreach ($post['ids'] as $k => $v) {
//            $where['id'][1][] = $v;
//        }
//
//
//        switch ($type) {
//            case 2:
//                $data = ['status' => 2];
//                break;
//            case 4:
//                $data = ['status' => 4];
//                break;
//            default:
//                $this->error('违规操作');
//        }
//
//
//        $update = Db::name('put_cash')->where($where)->update($data);
//
//        if ($update) {
//            $this->success('批量操作成功');
//        } else {
//            $this->error('批量操作失败');
//        }
//    }

    /**
     * @return mixed
     * 导出提现记录表格
     * gxq <know1111@vip.qq.com>
     */
    public function excel_put()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $post = $this->request->post();
            if (!$post) $this->error('违规操作');

            if (!isset($post['time'])) $this->error('请选择时间范围');
            if (!$post['time'][0] || !$post['time'][1]) $this->error('请选择时间范围');

            $id=Db::name('user')->where('uid',is_signin())->column('id');

            $time1 = $post['time'][0];
            $time2 = $post['time'][1];
            $data = Db::name('put_cash')
                ->alias('a')
                ->join('zc_user b', 'a.user_id=b.id')
                ->join('zc_user_card c', 'a.card_id=c.id')
                ->field('a.money,a.create_time,a.status,b.name,mobile,username,type,cardname,carnumber')
                ->where('a.create_time', '>=', $time1)
                ->where('a.create_time', '<=', $time2)
                ->where('a.user_id','in',$id)
                ->select();

            $user2 = array();
            foreach ($data as $k => $v) {
                $user2[$k][1] = $v['name'];
                $user2[$k][2] = $v['money'];
                $user2[$k][3] = $v['username'];
                $user2[$k][4] = $v['type'];
                $user2[$k][5] = $v['cardname'];
                $user2[$k][6] = $v['carnumber'];
                $user2[$k][7] = $v['mobile'];
                $user2[$k][8] = $v['create_time'];
                switch ($v['status']) {
                    case 1:
                        $user2[$k][9] = '待审核';
                        break;
                    case 2:
                        $user2[$k][9] = '审核通过';
                        break;
                    case 3:
                        $user2[$k][9] = '审核未通过';
                        break;
                    case 4:
                        $user2[$k][9] = '已打款';
                        break;
                    default :
                        $this->error('违规操作');
                };
            }

            $headArr = array('用户昵称', '提现金额', '银行卡持有人', '银行卡类型', '银行名称', '银行卡号', '手机号', '申请时间', '状态');
            $filename = "提现记录表";
            //dump($user2);exit;
            $this->getExcel($filename, $headArr, $user2);
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['daterange', 'time']
            ])
            ->method('post')
            ->isAjax(false)
            ->fetch();
    }


    private function getExcel($fileName, $headArr, $data)
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入

        vendor('PHPExcel/Classes/PHPExcel');
        $date = date("Y_m_d", time());
        $fileName .= "_{$date}";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }
        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        //print_r($data);exit;

        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");

            foreach ($rows as $keyName => $value) {// 列写入

                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        $count = count($data) + 1;
        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        //$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(24);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        //$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getStyle('N1:N' . $count)->getAlignment()->setWrapText(true);
        $objPHPExcel->getActiveSheet()->getStyle('A1:N' . $count)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A1:N' . $count)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码

        header('Content-type: application/vnd.ms-excel;charset=utf-8;name="' . 1 . '.xls"');
        header("Content-Disposition: attachment; filename=$fileName.xls");
        header('Cache-Control: max-age=0');
//header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
//header ('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}